import {
    Component,
    ElementRef,
    HostListener,
    OnInit,
    ViewChild
} from "@angular/core";
import { FetchService } from "../../../../core/net/fetch.service";
import * as _ from "lodash";
import { NzInputDirective, NzMessageService, NzModalService } from "ng-zorro-antd";
import * as moment from "moment";
import { FormBuilder, FormGroup } from "@angular/forms";
import { differenceInCalendarDays } from 'date-fns';
import { HttpClient } from '@angular/common/http';

@Component({
    selector: "app-mng-inlet",
    templateUrl: "./mng-inlet.component.html",
    styleUrls: ["../mng-water-report.component.scss"]
})
export class MngInletComponent implements OnInit {
    listData = [];
    sectionId = JSON.parse(localStorage.userInfo).sectionId;
    tempType = "1";
    contentTitle: string;
    today: Date = new Date();
    datePicker: Date = new Date();
    range: Date[];
    quickTimeSelect = null;
    tableData = [];
    widthConfig = ['120px', '75px', '75px', '50px', '50px', '50px', '50px', '50px', '50px', '50px', '50px', '50px', '50px', '50px', '50px'];
    basicOpts: any = {
        title: {
            left: 'center',
            textStyle: {
                color: "#777",
                fontSize: 16
            }
        },
        color: ['#1ada6f', '#ffbf44', '#12d0d2', '#0092f1', '#ffdc00', '#f9383b'],
        // grid: {
        //     top: '10%',
        //     left: '3%',
        //     right: '4%',
        //     bottom: '8%',
        //     containLabel: true
        // },
        tooltip: {
            trigger: "axis"
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['4h', '8h', '12h', '16h', '20h', '24h']
        },
        yAxis: {
            type: "value"
        },
        series: []
    };
    hasFlowChart: boolean = false;
    hasLevelChart: boolean = false;
    levelEchartsIntance: any;
    flowEchartsIntance: any;
    flowOpts: any = {};
    levelOpts: any = {};
    workNumEchartsIntance: any;
    workFlowEchartsIntance: any;
    workNumOpts: any = {};
    workFlowOpts: any = {};
    modalTableData = [];
    irrHistoryData = [];
    srId: string;

    modalTitle: string = "干渠进口水位流量历史数据";
    inletModalTitle: string = "干渠进口水位流量填报";
    modalNestedHead = [];
    modalShow: boolean = false;
    inletModalShow: boolean = false;
    inletFormList = [];
    editId: string | null;
    editCache: { [key: string]: { edit: boolean; data: any } } = {};

    inletCurrDate: Date = new Date();
    hour = '4';

    inletModalShow1: boolean = false;

    @ViewChild(NzInputDirective, { read: ElementRef }) inputElement: ElementRef;

    @HostListener("window:click", ["$event"])
    handleClick(e: MouseEvent): void {
        if (this.inputElement && e.target["tagName"] !== "INPUT") {
            Object.keys(this.editCache).forEach(key => {
                this.editCache[key].edit = null;
            });
        }
    }

    constructor(
        private fetchService: FetchService,
        private message: NzMessageService,
        private http: HttpClient,
        private fb: FormBuilder,
        private modal: NzModalService
    ) {
    }

    ngOnInit() {
        this.getDetailData();
    }
    levelChartInit(ec) {
        this.levelEchartsIntance = ec;
    }
    flowChartInit(ec) {
        this.flowEchartsIntance = ec;
    }
    workNumChartInit(ec) {
        this.workNumEchartsIntance = ec;
    }
    workFlowChartInit(ec) {
        this.workFlowEchartsIntance = ec;
    }
    updateEditCache(): void {
        this.tableData.forEach(item => {
            this.editCache[item.trId] = {
                edit: false,
                data: { ...item }
            };
        });
    }

    startEdit(trId: string, event: MouseEvent): void {
        event.preventDefault();
        event.stopPropagation();
        this.editCache[trId].edit = true;
        this.editId = trId;
    }

    getDetailData(): void {
        this.fetchService.post<any>("muw/wrsMuwWfData/list", {}).subscribe(res => {
            if (res) {
                this.tempType = res.irrType;
                this.tableData = res.wrsMuwWfDatas;
                // this.modalTableData = res.wrsMuwWfDatas;
                if (this.tableData.length > 0) {
                    this.srId = this.tableData[0].srId;
                    if (this.tempType === '1') {
                        this.selectedRow(this.tableData[0]);
                    } else if (this.tempType === '2') {
                        this.selectedRow(this.tableData, this.tableData[0].srName);
                    }
                }
            }
            this.updateEditCache();
        });
    }
    selectedRow(data, title?): void {
        console.log(data);
        const start = moment(this.today).subtract(7, "days").valueOf();
        const end = moment(this.today).valueOf();

        if (this.tempType === '2') {
            const params = {
                srId: data[0].srId,
                startDate: start,
                endDate: end
            };
            this.fetchService.post<any>('muw/wrsMuwWfData/historyDataList', params).subscribe(res => {
                res.forEach(item => {
                    item.time = moment(item.date).format("YYYY-MM-DD");
                });
                const xAxisArr = res.map(item => {
                    return item.time;
                });
                const legendArr = data.map(item => {
                    return item.trName;
                });
                const seriesWNData = data.map(item => {
                    const seriesData = [];
                    res.forEach(results => {
                        results.wrsMuwWfDatas.forEach(o => {
                            if (o.trName === item.trName) {
                                seriesData.push(parseFloat(o.workNum || '0') + parseFloat(o.workNumS || '0'));
                            }
                        });
                    });
                    return {
                        name: item.trName,
                        type: 'line',
                        data: seriesData
                    };
                });
                const seriesWFData = data.map(item => {
                    const seriesData = [];
                    res.forEach(results => {
                        results.wrsMuwWfDatas.forEach(o => {
                            if (o.trName === item.trName) {
                                seriesData.push(o.workFlow);
                            }
                        });
                    });
                    return {
                        name: item.trName,
                        type: 'line',
                        data: seriesData
                    };
                });
                const commonOpts = {
                    tooltip: {
                        trigger: "axis",
                        axisPointer: {
                            type: "line",
                            animation: false,
                            label: {
                                backgroundColor: "#505765"
                            }
                        }
                    },
                    legend: {
                        bottom: '4%',
                        data: legendArr
                    },
                    xAxis: {
                        data: xAxisArr,
                        axisLabel: {
                            interval: 0
                        }
                    },
                    color: ['#1ada6f', '#ffbf44', '#12d0d2', '#0092f1', '#ffdc00', '#f9383b']
                };
                this.workNumOpts = {
                    ...commonOpts, ...{
                        title: {
                            text: `${title}开机数量过程曲线`,
                            left: 'center',
                            textStyle: {
                                color: "#777",
                                fontSize: 16
                            },
                        },
                        yAxis: {
                            name: '开机数量(台)'
                        },
                        series: seriesWNData
                    }
                };
                this.workFlowOpts = {
                    ...commonOpts, ...{
                        title: {
                            text: `${title}开机流量过程曲线`,
                            left: 'center',
                            textStyle: {
                                color: "#777",
                                fontSize: 16
                            },
                        },
                        yAxis: {
                            name: '开机流量(m³/s)'
                        },
                        series: seriesWFData
                    }
                };
                this.workNumEchartsIntance.setOption(this.workNumOpts, true);
                this.workFlowEchartsIntance.setOption(this.workFlowOpts, true);
            });
        } else {
            this.hasLevelChart = !!data.wl;
            // this.hasFlowChart = !!data.flow;
            this.hasFlowChart = true;
            setTimeout(() => {
                this.resizeChart();
            });
            this.flowOpts = {
                title: {
                    text: `${data.trName}流量过程历时曲线`
                },
                legend: {
                    bottom: 0,
                    data: ['限定流量', '实际流量']
                },
                yAxis: {
                    name: '流量(m³/s)'
                },
                series: [
                    {
                        name: '限定流量',
                        type: 'line',
                        data: [data.flow, data.flow, data.flow, data.flow, data.flow, data.flow]
                    },
                    {
                        name: '实际流量',
                        type: 'line',
                        data: [data.flowFour, data.flowEight, data.flowTwelve, data.flowSixteen, data.flowTwenty, data.flowTwentyFour]
                    }
                ]
            };
            this.levelOpts = {
                title: {
                    text: `${data.trName}水位过程历时曲线`
                },
                yAxis: {
                    name: '水位(m)'
                },
                legend: {
                    bottom: 0,
                    data: ['警戒水位', '实际水位']
                },
                series: [
                    {
                        name: '警戒水位',
                        type: 'line',
                        data: [data.wl, data.wl, data.wl, data.wl, data.wl, data.wl]
                    },
                    {
                        name: '实际水位',
                        type: 'line',
                        data: [data.wlFour, data.wlEight, data.wlTwelve, data.wlSixteen, data.wlTwenty, data.wlTwentyFour]
                    }
                ]
            };
        }

    }

    resizeChart() {
        if (this.levelEchartsIntance) { this.levelEchartsIntance.resize(); }
        if (this.flowEchartsIntance) { this.flowEchartsIntance.resize(); }
    }

    submit(): void {
        this.modal.confirm({
            nzTitle: '确认提交并上报？',
            nzContent: '',
            nzOnOk: () => {
                const table = _.cloneDeep(this.tableData);
                const data = table.map(item => {
                    return _.assign(item, { statu: 2 });
                });
                this.fetchService.post<any>("muw/wrsMuwWfData/addOld", data).subscribe(res => {
                    this.message.success("提交成功");
                    this.getDetailData();
                });
            }
        });
    }

    save(): void {
        const table = _.cloneDeep(this.tableData);
        const data = table.map(item => {
            return _.assign(item, { statu: 1 });
        });
        this.fetchService.post<any>("muw/wrsMuwWfData/addOld", data).subscribe(res => {
            this.message.success("暂存成功");
            this.getDetailData();
        });
    }

    //  进水流量填报
    openInletModal(): void {
        this.inletModalShow = true;
        this.inletCurrDate = new Date();
        this.hour = this.getHour(new Date());
        this.getInletDetailData();
    }
    //  日均流量填报
    openInletModal1(): void {
        this.inletModalShow1 = true;
        this.inletCurrDate = new Date();
        this.hour = '100';
        this.getInletDetailData();
    }
    disabledDate = (current: Date): boolean => {
        return differenceInCalendarDays(current, new Date()) > 0;
    }
    private getHour(time): string {
        const curHour = moment(time).hour();
        if (curHour >= 0 && curHour < 4) {
            return '4';
        } else if (curHour >= 4 && curHour < 8) {
            return '8';
        } else if (curHour >= 8 && curHour < 12) {
            return '12';
        } else if (curHour >= 12 && curHour < 16) {
            return '16';
        } else if (curHour >= 16 && curHour < 20) {
            return '20';
        } else {
            return '24';
        }
    }
    openDetailModal(): void {
        this.modalShow = true;
        if (this.tempType === "2") {
            this.quickTimeSelect = "7";
            this.quickSelect();
        } else {
            this.queryInfo(this.today);
        }
    }

    export(): void {
        const param = {};
        this.fetchService.export('muw/wrsMuwWfData/export', param).subscribe((res: any) => {
            const blob = new Blob([res], { type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8' });
            const elink = document.createElement('a');

            elink.download = `干渠进水口水位流量表.xlsx`;
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }

    print(): void {
    }

    onModalCancel() {
        this.modalShow = false;
    }

    onInletModalCancel() {
        this.inletModalShow = false;
    }

    inletSubmit(type?) {
        this.modal.confirm({
            nzTitle: '确认提交并上报？',
            nzContent: '',
            nzOnOk: () => {
                const data = _.cloneDeep(this.modalTableData).map((item, index) => {
                    const formVaule = this.inletFormList[index].form.value;
                    if (type) {
                        formVaule.flow = formVaule.flowAvg;
                    }
                    return _.assign(item, this.inletFormList[index].form.value);
                });
                console.log(data);
                const params = {
                    date: moment(this.inletCurrDate).valueOf(),
                    hour: this.hour,
                    wrsMuwWfDatas: data
                };
                this.fetchService
                    .post<any>("muw/wrsMuwWfData/add", params, { showError: false })
                    .subscribe(res => {
                        if (res && res.code && res.code !== 200) {
                            this.message.warning(res.msg);
                        } else {
                            this.message.success("填报成功");
                            this.getDetailData();
                        }
                        this.inletModalShow = false;
                        this.inletModalShow1 = false;
                    });
            }
        });
    }

    queryInfo(date): void {
        const time = moment(date).valueOf();
        this.fetchService
            .post<any>("muw/wrsMuwWfData/list", { time: time })
            .subscribe(res => {
                if (res) {
                    this.modalTableData = res.wrsMuwWfDatas;
                }
            });
    }

    onRangeChange(result: Date[] | number[]): void {
        const start = result[0] ? moment(result[0]).valueOf() : moment().valueOf();
        const end = result[1] ? moment(result[1]).valueOf() : moment().valueOf();
        const params = {
            srId: this.srId,
            startDate: start,
            endDate: end
        };
        this.fetchService
            .post<any>("muw/wrsMuwWfData/historyDataList", params)
            .subscribe(res => {
                res.forEach(data => {
                    data.time = moment(data.date).format("YYYY-MM-DD");
                });
                if (res.length) {
                    this.modalNestedHead = res[0].wrsMuwWfDatas.map(item => {
                        return item.trName;
                    });
                }
                this.irrHistoryData = _.reverse(res);
            });
    }

    quickSelect(): void {
        const start = moment()
            .subtract(parseInt(this.quickTimeSelect, 10), "days")
            .valueOf();
        const end = moment().valueOf();
        this.onRangeChange([start, end]);
    }

    getInletDetailData(): void {
        this.inletFormList = [];
        const params = {
            date: moment(this.inletCurrDate).valueOf(),
            hour: this.hour
        };
        this.fetchService.post('muw/wrsMuwWfData/listByTime', params).subscribe(res => {
            this.modalTableData = res['wrsMuwWfDatas'];
            this.modalTableData.forEach(item => {
                const form: FormGroup = this.fb.group({
                    wl: [item.wl],
                    flow: [item.flow],
                    flowAvg: [item.flowAvg]
                });
                this.inletFormList.push({
                    stadiaCode: item.stadiaCode,
                    name: item.trName,
                    form: form
                });
            });
        });

    }
}
